package com.fuchen.academic.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 字符串工具类
 *
 */
public class StringUtil {

	/**
	 * 判断字符串是否为空，不为空时返回true，否则返回false
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str){
		if(null != str && str.trim().length() > 0){
			return true;
		}
		return false;
	}
	
	/**
	 * 判断字符串数组里是否有空值，若有任一字符串为空，则返回false
	 * 当全部不为空时，返回true
	 * @param strs
	 * @return
	 */
	public static boolean isNotEmpty(String ... strs){
		if(null!=strs && strs.length > 0){
			
			for(String str : strs){
				if(!isNotEmpty(str)){
					return false;
				}
			}
			
			return true;
		}
		return false;
	}
	
	/**
	 * HTML中特殊字符转换
	 * @param str
	 * @return
	 */
	public static String htmlspecialchars(String str) {
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		return str;
	}
	
	/**
	 * Reader转换成字符串
	 * @param reader
	 * @return
	 * @throws IOException
	 */
	public static String readerToString(Reader reader) throws IOException{
		BufferedReader bufReader = new BufferedReader(reader);
		StringBuilder builder = new StringBuilder();
		String tmp = "";
		while((tmp = bufReader.readLine())!=null){
			builder.append(tmp);
		}
		reader.close();
		return builder.toString();
	}
	
	/**
	 * 将数字型的字符串数组转换成整型数组
	 * @param strs
	 * @return
	 */
	public static Integer[] changeToIntArr(String[] strs){
		if(null == strs || strs.length == 0){
			return null;
		}
		Integer[] intArr = new Integer[strs.length];
		
		for(int i=0;i<strs.length;i++){
			intArr[i] = Integer.parseInt(strs[i]);
		}
		
		return intArr;
	}
	
	/**
	 * 返回32位的UUID字符串
	 * @return
	 */
	public static String getUUID(){
		return UUID.randomUUID().toString().replace("-", "").toLowerCase();
	}
	
	/**
	 * 数据加密（MD5）
	 * @param plainText
	 * @return
	 */
    public static String getMd5(String plainText) {  
        try {  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            md.update(plainText.getBytes());  
            byte b[] = md.digest();  
  
            int i;  
  
            StringBuffer buf = new StringBuffer("");  
            for (int offset = 0; offset < b.length; offset++) {  
                i = b[offset];  
                if (i < 0)  
                    i += 256;  
                if (i < 16)  
                    buf.append("0");  
                buf.append(Integer.toHexString(i));  
            }  
            //32位加密  
            return buf.toString();  
            // 16位的加密  
            //return buf.toString().substring(8, 24);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
            return null;  
        }  
  
    }  
}
